<template>
  <Layout style="height: 100%" class="main">
    <Header>
      <Menu mode="horizontal" theme="dark" active-name="1">
        <div class="logo-v3">
          <img :src="logoTime" class="hd-img-responsive"/>
        </div>
        <!-- <div style="width: 870px;">
          <img :src="adPic" class="hd-img-responsive"/>
        </div> -->
        <div class="login-info">
          <div class="user-info">
            <span>{{personData.name}}</span> [{{personData.company_name}}]
          </div>
          <div class="logout-btn logout-btn-item" @click="showErcode(codeUrl)">
            <Icon type="md-key"/>
            绑定
          </div>
          <div class="logout-btn logout-btn-item" @click="passwordInfo.show=true">
            <Icon type="md-create"/>
            修改密码
          </div>
          <Modal v-model="modalQr" title="二维码" width="500" cancel-text="关闭"
                 @on-ok="modalQr = false" @on-cancel="modalQr = false" ok-text="确定" style="position:relative;">
            <div id="qrcode" ref="qrcode" style="margin-left: 18%"></div>
            <div style="text-align: center;margin-top: 10px;font-size: 1rem;">扫描二维码绑定用户信息</div>
          </Modal>
          <div class="logout-btn logout-btn-item" @click="logout">
            <Icon type="md-log-out"/>
            注销
          </div>
          <!-- <div class="logout-btn btn-itemoption"><Icon type="ios-settings-outline" />设置</div> -->
        </div>
        <div class="header-split-v3"></div>
      </Menu>
    </Header>
    <Layout>
      <Modal v-model="display_model1_obj.modal1" :title="display_model1_obj.text" width="900">
        <div id="printMe">
          <Form label-position="right" :label-width="100">
            <Row>
              <Col span="24" class="ivu-form-item-content" style="text-align: center">
                <embed width="800" height="600" :src="display_model1_obj.filepath"></embed>
              </Col>
            </Row>
          </Form>
        </div>
        <div slot="footer">
          <!-- <Button type="success" size="large" v-print="'#printMe'">打印</Button> -->
          <Button type="error" size="large" @click="display_model1_obj.modal1=false">关闭</Button>
        </div>
      </Modal>
      <Modal v-model="passwordInfo.show" title="修改密码" width="600" :closable="false" :mask-closable="false">
        <Form label-position="right" :label-width="100" ref="passwordInfo" :model="passwordInfo" :rules="ruleInline">
          <FormItem prop="oldpassword" label="旧密码：" class="set-password-input">
            <Input type="password" v-model="passwordInfo.oldpassword"></Input>
          </FormItem>
          <FormItem prop="newpassword" label="新密码：" class="set-password-input">
            <Input type="password" v-model="passwordInfo.newpassword"></Input>
          </FormItem>
          <FormItem prop="repassword" label="确认密码：" class="set-password-input">
            <Input type="password" v-model="passwordInfo.repassword"></Input>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="success" size="large" @click="setPassWord('passwordInfo')">确认</Button>
          <Button type="error" size="large" @click="closePassWord('passwordInfo')">关闭</Button>
        </div>
      </Modal>
      <Sider hide-trigger collapsible :width="256" :collapsed-width="64" v-model="collapsed" class="left-sider"
             :style="{overflow: 'hidden',maxHeight: maxH+'px'}">
       <!-- <li class="menu-title-v3">
          <span>社区便民服务事项清单</span><br/>
          <span>部门数（{{totalBMNum - 1}}） | 事项数（{{totalItemNum}}）</span>
        </li>-->
       <!-- <div class="search-frame">
          <Input search placeholder="事项关键字" v-model="searchName" @on-change="searchList1"
                 @on-search="searchList" class="search-input"/>
        </div>-->
       <!-- <three-menu v-if="!reloadItem" :menu-list="treeDataList" @on-select="viewProcess"></three-menu>-->
        <Menu  theme="primary" active-key="1" @on-select="toMessage">
<!--          <MenuItem :name="index" v-for="(item,index) in daohang" v-bind:key="index" :value="item">-->
<!--            <Icon type="md-document" />-->
<!--            {{item}}-->
<!--          </MenuItem>-->
          <Menu-item name=0>
            <Icon type="logo-buffer" />
            首页
          </Menu-item>
          <Menu-item name=1>
            <Icon type="md-laptop" />
            工作列表
          </Menu-item>
            <Menu-item name=2>
              <Icon type="ios-folder-open-outline" />
              异地受理
            </Menu-item>
            <Menu-item name=3>
              <Icon type="md-folder-open" />
              通讯簿
            </Menu-item>
            <Menu-item name=4>
              <Icon type="ios-folder" />
              法律法规
            </Menu-item>
            <Menu-item name=5>
              <Icon type="md-menu" />
              通知指南
            </Menu-item>
            <Menu-item name=6>
              <Icon type="md-stats" />
              统计
            </Menu-item>
            <Menu-item name=7>
              <Icon type="ios-paper" />
              网格一张图
            </Menu-item>
            <Menu-item name=8>
              <Icon type="md-stats"></Icon>
              绩效数据
            </Menu-item>
          <Submenu name="9">
            <template slot="title">
              <Icon type="ios-paper" />
              社区台账
            </template>
            <MenuItem name="9-1">社区人员台账</MenuItem>
            <MenuItem name="9-2" >网格化数据台账</MenuItem>
            <MenuItem name="9-3" >党组织工作台账</MenuItem>
            <MenuItem name="9-4" >社会组织工作台账</MenuItem>
          </Submenu>
          <Submenu name="10">
            <template slot="title">
              <Icon type="ios-paper" />
              日常工作
            </template>
            <MenuItem name="10-1">日常工作列表</MenuItem>
          </Submenu>
          <Submenu name="11">
            <template slot="title">
              <Icon type="ios-paper" />
              公共服务工作
            </template>
            <MenuItem name="11-1">公共服务工作列表</MenuItem>
          </Submenu>
          <Submenu name="12">
            <template slot="title">
              <Icon type="ios-paper" />
              活动组织
            </template>
            <MenuItem name="12-1">活动组织列表</MenuItem>
          </Submenu>
        </Menu>
      </Sider>
      <Layout class="content-layout-v3" :style="{overflow: 'hidden',maxHeight: maxH+'px',overflowY:'scroll'}">
        <Breadcrumb>
          <BreadcrumbItem v-for="(route, index) in routeList" v-bind:key="index" :to="route.path">
            <span :class="{turnBlue: route.state}" @click="changeRoute(index)">
              <Icon :type="route.icon"/> {{route.name}}
            </span>
          </BreadcrumbItem>
        </Breadcrumb>
        <Content :style="{padding: '15px', background: '#fff'}">
          <router-view></router-view>
        </Content>
      </Layout>
    </Layout>
  </Layout>
</template>

<script>
import './index.less'
import logoTime from '@/assets/images/2.png'
import { mapActions } from 'vuex'
import { updatePwd } from '@/api/user'
import { setSeparateNotice, treelist, getCodeUrl } from '@/api/eventlist'
import ThreeMenu from './three-menu'
// import { setInterval, clearInterval } from 'timers'
import QRCode from 'qrcodejs2'
// import $ from 'jquery'
export default {
  components: {
    ThreeMenu
  },
  data () {
    const validatePassCheck = (rule, value, callback) => {
      if (value !== this.passwordInfo.newpassword) {
        callback(new Error('确认密码与新密码不相同'))
      } else {
        callback()
      }
    }
    return {
      tubiao: '',
      daohang: ['首页', '工作列表', '异地受理', '通讯簿', '法律法规', '通知指南', '统计', '网格一张图', '绩效数据'],
      codeUrl: '',
      company_codes: '',
      loginNames: '',
      modalQr: false,
      timerInterval: null,
      collapsed: false,
      reloadItem: false,
      logoTime,
      totalItemNum: 0,
      totalBMNum: 0,
      treeDataList: [],
      searchName: '',
      personData: {},
      routeList: [],
      passwordInfo: { show: false },
      display_model1_obj: { modal1: false, filepath: '' },
      maxH: `${document.documentElement.clientHeight}` - 64,
      ruleInline: {
        oldpassword: [
          { required: true, message: '请填写旧密码', trigger: 'blur' }
        ],
        newpassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        repassword: [
          { required: true, message: '请填写确认密码', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
          { validator: validatePassCheck, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    menuList () {
      return this.treeDataList
    }
  },
  methods: {
    toMessage (name) {
      console.log(name)
      if (name === '0') {
        this.tubiao = 'md-bluetooth'
        this.$router.push({
          name: 'mainv3'
        })
      } else if (name === '1') {
        this.$router.push({
          name: 'workbench'
        })
      } else if (name === '2') {
        this.$router.push({
          name: 'separateservice'
        })
      } else if (name === '3') {
        this.$router.push({
          name: 'telnote'
        })
      } else if (name === '4') {
        this.$router.push({
          name: 'knowledgebase'
        })
      } else if (name === '5') {
        this.$router.push({
          name: 'message'
        })
      } else if (name === '6') {
        this.$router.push({
          name: 'closingratelist'
        })
      } else if (name === '7') {
        this.$router.push({
          name: 'grid'
        })
      } else if (name === '8') {
        this.$router.push({
          name: 'performance'
        })
      } else if (name === '9-1') {
        this.$router.push({
          name: 'community-personnel-ledger'
        })
      } else if (name === '9-2') {
        this.$router.push({
          name: 'grid-data-account'
        })
      } else if (name === '9-3') {
        this.$router.push({
          name: 'party-work-ledger'
        })
      } else if (name === '9-4') {
        this.$router.push({
          name: 'social-organization-account'
        })
      }
    },
    ...mapActions([
      'handleLogOut'
    ]),
    logout () {
      this.handleLogOut().then(() => {
        // clearInterval(this.timerInterval)
        this.$router.push({
          name: 'login'
        })
      })
    },
    closePassWord (name) {
      this.passwordInfo.show = false
      this.$refs[name].resetFields()
    },
    setPassWord (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          updatePwd(this.passwordInfo).then(res => {
            if (res.data.data) {
              this.$Notice.success({ title: '修改成功', desc: '修改密码后需要重新登录' })
              this.passwordInfo.show = false
              this.logout()
            } else {
              this.$Notice.error({ title: '修改失败', desc: res.data.errmsg })
            }
          })
        } else {
          this.$Notice.error({ title: '信息错误', desc: '密码修改信息错误，请重新填写' })
        }
      })
    },
    viewProcess (item) {
      if (item.filepath) {
        this.display_model1_obj.text = item.type_name
        this.display_model1_obj.modal1 = true
        this.display_model1_obj.filepath = item.filepath
      } else {
        this.$Notice.error({ title: '无文件', desc: '当前事项无PDF说明文档' })
      }
    },
    searchList1 () {
      if (!this.searchName) {
        this.searchList()
      }
    },
    searchList () {
      this.reloadItem = true
      this.treeDataList.forEach(e1 => {
        e1.hidden = true
        if (e1.children) {
          let curNum1 = 0
          e1.children.forEach(e2 => {
            if (e2.children) {
              let curNum2 = 0
              e2.children.forEach(e3 => {
                e3.hidden = true
                if (e3.type_name.indexOf(this.searchName) >= 0) {
                  e3.hidden = false
                  curNum2++
                  curNum1++
                }
              })
              e2.hidden = true
              if (curNum2 > 0) {
                e2.count = curNum2
                e2.hidden = false
              }
            } else {
              e2.hidden = true
              if (e2.type_name.indexOf(this.searchName) >= 0) {
                e2.hidden = false
                curNum1++
              }
            }
          })
          if (curNum1 > 0) {
            e1.count = curNum1
            e1.hidden = false
          }
        } else {
          if (!this.searchName) {
            e1.hidden = false
          }
        }
      })
      this.$nextTick(() => {
        this.reloadItem = false
      })
    },
    changeRoute (index) {
      this.routeList.forEach(element => {
        element.state = false
      })
      this.routeList[index].state = true
    },
    getTreeList () {
      treelist().then(ret => {
        let result = ret.data.data
        this.treeDataList = result
        if (this.treeDataList !== undefined) {
          this.treeDataList.forEach(element => {
            element.count = element.count || 0
            if (element.children) {
              this.totalBMNum += 1
              element.children.forEach(e2 => {
                if (e2.children) {
                  e2.count = e2.children.length || 0
                  element.count += e2.count
                }
              })
              element.count = element.count || element.children.length
            }
            this.totalItemNum += element.count
          })
        }
      })
    },
    showErcode (codeUrl) {
      console.log('弹出二维码')
      // let qrcodeEL = document.getElementById('qrcode')
      // let qrcode = new QRCode(qrcodeEL)
      document.getElementById('qrcode').innerHTML = ''
      this.modalQr = true
      this.getCode(codeUrl)
      // qrcode.clear() // clear the code.
      // qrcode.makeCode(codeUrl) // make another code.
    },
    getCode (codeUrl) {
      var qrcode = new QRCode(document.getElementById('qrcode'), {
        text: codeUrl,
        top: 200,
        width: 300,
        height: 300,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      return qrcode
    },
    // 根据权限隐藏事项操作
    permission_display () {
      /*      if (this.company_codes !== 'LM') {
        let tempList = []
        this.routeList.forEach((element, index) => {
          if (element.path === '/itemoption') {
          } else {
            tempList.push(element)
          }
        })
        this.routeList = tempList
      } */
    },
    setFlowSee (id) {
      setSeparateNotice(id).then(res => {
      })
    },
    toSeparate () {
      let router = this.$store.state.app.mainv3Nav
      router.forEach(element => {
        element.state = false
      })
      router[2].state = true
      this.$router.push({
        name: 'separateservice',
        params: { tabindex: 1 }
      })
    }
  },
  mounted () {
    let severUserInfo = this.$store.state.user.severUserInfo
    this.company_codes = severUserInfo.company_code
    this.loginNames = severUserInfo.loginName
    this.personData.name = severUserInfo.name
    this.personData.company_name = severUserInfo.company_name
    getCodeUrl(this.company_codes, this.loginNames).then(res => {
      this.codeUrl = res.data.result.url
    })
    this.routeList = this.$store.state.app.mainv3Nav
    this.getTreeList()
    this.permission_display()
    // this.timerInterval = setInterval(() => {
    //   getSeparateNotice().then(res => {
    //     res.data.data.forEach(element => {
    //       this.$Notice.close(element.id)
    //       this.$Notice.info({
    //         title: '您有新的收受分离事项！',
    //         duration: 0,
    //         name: element.id,
    //         render: h => {
    //           return h('span', [
    //             element.title,
    //             h('Button', {
    //               props: { type: 'primary', size: 'small' },
    //               style: { marginLeft: '10px' },
    //               on: {
    //                 click: () => {
    //                   this.setFlowSee(element.id)
    //                   this.toSeparate()
    //                   this.$Notice.close(element.id)
    //                 }
    //               }
    //             }, '查看')
    //           ])
    //         },
    //         onClose: () => {
    //           this.setFlowSee(element.id)
    //         }
    //       })
    //     })
    //   })
    // }, 10000)
  }
}
</script>
